const BASE_URL = "https://www.txiaomai.com/ph/public/common" //请求地址


const requestPromise = (url, requestMethod = 'GET', requestBody, header) => {
  // 返回一个promise对象
  if (!url) {
    return "api不合法"
  }
  let myHeader = {
    'content-type': 'application/json' // 默认值
  }
  if (Object.keys(header).length > 0) {
    myHeader = {
      ...header
    }
    myHeader['content-type'] = 'application/json'
  }

  return new Promise((resolve, reject) => {
    // 显示加载中loading效果
    wx.showLoading({
      title: "加载中",
      mask: true //开启蒙版遮罩
    });
    wx.request({
      url: BASE_URL + url,
      method: requestMethod,
      data: requestBody,
      header: myHeader,
      success: (result) => {
        // 请求成功，就将成功的数据返回出去
        if (result.data.code == 0) {
          // 请求成功
          resolve({
            status: true,
            result: result.data.data
          })
        } else {
          wx.showToast({
            title: '请求失败',
            icon: 'error',
            duration: 1000 //持续的时间
          })
          resolve({
            status: false,
            result: result.data
          })
        }
        //  关闭正在等待loading效果
        wx.hideLoading();
      },
      fail: (err) => {
        reject(err)
        //  关闭正在等待loading效果
        wx.hideLoading();
      },
    })
  })
}

export async function requestAsync(url, requestMethod = 'GET', requestBody, header) {
  try {
    const res = await requestPromise(url, requestMethod, requestBody, header);
    return res;
  } catch (error) {
    return error;
  }
}